package xyz.pyming.utils.http;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CountDownLatch;

public class ThreadDownloadManager {
    public static String flag = "1";
    private String uri;
    private String target;
    /**
     * 线程计数同步辅助
     */
    private CountDownLatch latch;

    public ThreadDownloadManager(String uri, String target) {

        System.out.println("实际文件地址：" + uri);
        System.out.println("文件检测");
        this.target = target;
        this.uri = uri;
        try {
            if (new File(target).exists() == false) {
                System.out.println("创建文件");
                new File(target).createNewFile();
            } else {
                System.out.println("删除后创建文件");
                new File(target).delete();
                new File(target).createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
            flag = "1";
        }
    }


    public boolean download() throws InterruptedException, IOException {
        System.out.println(uri);
        //获取文件总大小
        int totalSize = 0;
        System.out.println("主线程开始请求");
        HttpURLConnection connection = (HttpURLConnection) new URL(uri).openConnection();
        connection.connect();
        int contentLength = connection.getContentLength(); //文件大小
        System.out.println("文件大小：" + contentLength);
        totalSize = contentLength;   //文件大小
        connection.disconnect();
        //将文件分片并分开下载
        int num = 30 * 1024 * 1024;
        int threadCount = totalSize % num == 0 ? (totalSize / num) : (totalSize / num) + 1;  //预计线程数量
        int perThreadSize = totalSize / threadCount;//每一个线程分到的任务下载量
        int threadCount2 = totalSize % perThreadSize == 0 ? (totalSize / perThreadSize) : (totalSize / perThreadSize) + 1; //实际线程数量
        int id = 0;
        int from = 0, to = 0;
        System.out.println("实际线程数量：" + threadCount2);
        latch = new CountDownLatch(threadCount2);
        while (totalSize > 0) {
            id++;
            to = totalSize;
            from = totalSize - perThreadSize;  //开始坐标为  剩余坐标 -每次坐标
            if (from < 0) {
                from = 0;               //开始坐标小于0 为0
            }
            totalSize -= perThreadSize;
            //开始下载
            UnitDownloader downloader = new UnitDownloader(from, to, new File(target), uri, id, latch);
            new Thread(downloader).start();
        }
        latch.await();
        if (flag.equals("1")) {
            System.out.println("下载完成开始加密");
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(target));
            String newFilePath = target.replaceAll("zzzzz", "");
            System.out.println("真实地址：" + newFilePath);
            if (!new File(newFilePath).getParentFile().exists() && !new File(newFilePath).getParentFile().isDirectory()) {
                new File(newFilePath).getParentFile().mkdirs();
            }
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFilePath));
            int n;
            while ((n = bis.read()) != -1) {
                bos.write(n + 123);
            }
            bis.close();
            bos.close();
            new File(target).delete();
            return true;
        }
        return false;
    }

}
